<!-- src/components/DataChart/LineChart.vue -->
<template>
    <div ref="chartContainer" class="line-chart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';

interface SeriesItem {
    name: string;
    data: (string | number)[];
    type?: string;
    smooth?: boolean;
    color?: string;
    lineStyle?: any;
    itemStyle?: any;
    areaStyle?: any;
}

interface Props {
    title?: string;
    xAxisData?: (string | number)[];
    seriesData?: (string | number)[];
    seriesName?: string;
    seriesList?: SeriesItem[];
    yAxisName?: string;
    xAxisName?: string;
    height?: string;
    width?: string;
    yAxisMin?: number;
    yAxisMax?: number;
    showLegend?: boolean;
    enableDataZoom?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
    title: '',
    xAxisData: () => [],
    seriesData: () => [],
    seriesName: '数据',
    seriesList: () => [],
    yAxisName: '',
    xAxisName: '',
    height: '400px',
    width: '100%',
    yAxisMin: undefined,
    yAxisMax: undefined,
    showLegend: false,
    enableDataZoom: false
});

const chartContainer = ref<HTMLElement | null>(null);
let myChart: echarts.ECharts | null = null;

// 默认颜色调色板
const colorPalette = [
    '#5470c6', // 蓝色
    '#d65a8d', // 玫红色（偏紫的玫红色）
    '#ee6666', // 红色
    '#91cc75', // 浅绿色
    '#fac858', // 黄色
    '#73c0de', // 浅蓝色
    '#3ba272', // 绿色
    '#fc8452', // 橙色
    '#9a60b4', // 紫色
    '#ea7ccc', // 粉色
    '#ff7f7f',//浅红色 
];

const initChart = async () => {
    if (!chartContainer.value) return;
    myChart = echarts.init(chartContainer.value);
    updateChart();
};

const updateChart = async () => {
    if (!myChart) return;

    try {
        let seriesConfig: any[] = [];

        // 处理 seriesList 情况（多条线）
        if (props.seriesList && props.seriesList.length > 0) {
            seriesConfig = props.seriesList.map((series, index) => {
                // 如果用户提供了颜色，则使用用户提供的颜色，否则使用调色板中的颜色
                const baseColor = series.color || colorPalette[index % colorPalette.length];

                return {
                    name: series.name,
                    type: series.type || 'line',
                    data: series.data,
                    smooth: series.smooth !== undefined ? series.smooth : true,
                    symbolSize: 6,
                    lineStyle: {
                        width: series.lineStyle?.width || 2,
                        color: series.lineStyle?.color || baseColor,
                        type: series.lineStyle?.type || 'solid' // 支持线型设置（solid, dashed, dotted）
                    },
                    itemStyle: {
                        color: series.itemStyle?.color || baseColor
                    },
                    areaStyle: series.type === 'area' ? {
                        opacity: series.areaStyle?.opacity || 0.1,
                        color: series.areaStyle?.color || baseColor
                    } : undefined
                };
            });
        }
        // 处理 seriesData 情况（单条线）
        else if (props.seriesData && props.seriesData.length > 0) {
            seriesConfig = [{
                name: props.seriesName,
                type: 'line',
                data: props.seriesData,
                smooth: true,
                symbolSize: 6,
                lineStyle: {
                    width: 2,
                    color: colorPalette[0]
                },
                itemStyle: {
                    color: colorPalette[0]
                },
                areaStyle: {
                    opacity: 0.1,
                    color: colorPalette[0]
                }
            }];
        }

        const option: echarts.EChartsOption = {
            title: {
                text: props.title,
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            },
            legend: props.showLegend ? {
                data: seriesConfig.map(s => s.name),
                top: '10%',
                textStyle: {
                    fontSize: 12
                }
            } : undefined,
            tooltip: {
                trigger: 'axis',
                backgroundColor: 'rgba(255, 255, 255, 0.9)',
                borderColor: '#ccc',
                borderWidth: 1,
                textStyle: {
                    color: '#333'
                },
                padding: [10, 15],
                formatter: (params: any) => {
                    let tooltip = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].name}</div>`;
                    params.forEach((item: any) => {
                        tooltip += `<div>
              <span style="display: inline-block; width: 10px; height: 10px; background-color: ${item.color}; border-radius: 50%; margin-right: 5px;"></span>
              ${item.seriesName}: ${item.value}
            </div>`;
                    });
                    return tooltip;
                }
            },
            grid: {
                left: '8%',
                right: '8%',
                bottom: '15%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: props.xAxisData,
                axisTick: {
                    alignWithLabel: true
                },
                name: props.xAxisName,
                nameLocation: 'middle',
                nameGap: 30
            },
            yAxis: {
                type: 'value',
                name: props.yAxisName,
                min: props.yAxisMin,
                max: props.yAxisMax
            },
            axisLabel: {
                rotate: 0,
                interval: 0,
                formatter: (value: string | number) => value.toString()
            },
            series: seriesConfig,
            dataZoom: props.enableDataZoom ? [
                {
                    type: 'inside',
                    start: 0,
                    end: 100
                },
                {
                    type: 'slider',
                    start: 0,
                    end: 100,
                    height: 20,
                    bottom: 10
                }
            ] : undefined
        };

        myChart.setOption(option);
    } catch (error) {
        console.error('更新折线图失败:', error);
    }
};

const handleResize = () => {
    if (myChart) myChart.resize();
};

watch(() => [
    props.xAxisData,
    props.seriesData,
    props.seriesList,
    props.title,
    props.yAxisMin,
    props.yAxisMax,
    props.showLegend,
    props.enableDataZoom
], () => {
    updateChart();
});

onMounted(() => {
    initChart();
    window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize);
    if (myChart) myChart.dispose();
});
</script>

<style lang="scss" scoped>
$primary-color: #5470c6;
$border-color: #ddd;

.line-chart-container {
    width: v-bind(width);
    height: v-bind(height);
    margin: 0 auto;
    border: 1px solid $border-color;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    @media (max-width: 768px) {
        width: 100%;
        height: 300px;
    }
}
</style>